<?php

class Academico_LaboratorioalumnoController extends Zend_Controller_Action {

    private $log;

    public function init() {
        $this->log = Zend_Registry::get(VirtualLabs_Common::DEBUG_LOG);
    }

    public function preDispatch() {
        // Autenticacion del usuario
        $auth = Zend_Auth::getInstance();
        if (!$auth->hasIdentity()) {
            $this->_helper->layout->disableLayout();
            $this->_forward("index", "index", "");
        } else {
            $identity = $auth->getIdentity();
            if ($identity['tipo_usuario'] == VirtualLabs_Admin_Usuario::ROL_ADMIN) {
                $this->_helper->layout->disableLayout();
                $this->_redirect('/');
            }
        }
        //fin de la autenicacion del usuario
    }

    public function indexAction() {
        
    }

    public function labAction() {
        $this->view->codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');
        try {
            $lab = new VirtualLabs_Admin_Laboratorio();
            $datosLaboratorio = $lab->getLaboratorio('*', array('codigo_laboratorio' => array('criteria' => '=', 'value' => $this->getRequest()->getParam('codigo_laboratorio'))));
            $this->view->nombreLaboratorio = $datosLaboratorio['nombre'];
            $this->view->descripcion = $datosLaboratorio['descripcion'];
            $this->view->fechaCreacion = $datosLaboratorio['fecha_hora_creacion'];
            $this->view->fechaInicio = $datosLaboratorio['fecha_inicio'];
            $this->view->fechaFin = $datosLaboratorio['fecha_fin'];
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
        }
    }

    public function vminlabAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $codigoLaboratorio = $this->getRequest()->getParam('codigo_laboratorio');

        $vmDao = new VirtualLabs_Academico_Machine();
        $identity = Zend_auth::getInstance()->getIdentity();
        $machines = $vmDao->getVmsInLab($codigoLaboratorio, $identity['username']);

        $response = array();

        foreach ($machines as $vm) {
            $this->log->debug("codigo_vm : " . var_dump($vm['codigo_vm']));
            if ($vm['codigo_vm'] != null) {
                $cloudData = $vmDao->getVmData($vm['codigo_vm']);
                $vmCloudSummary = array('name' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['name'],
                    'displayname' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['displayname'],
                    'hostid' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['hostid'],
                    'cpuspeed' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['cpuspeed'],
                    'cpunumber' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['cpunumber'],
                    'serviceofferingname' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['serviceofferingname'],
                    'memory' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['memory'],
                    'ipaddress' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic']['ipaddress'],
                    'networkname' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic']['networkname'],
                    'gateway' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic']['gateway']);

                $response[] = array("<a id='{$vm['codigo_maquina_virtual']}' href='/academico/maquinaalumno/vm/codigo_maquina_virtual/{$vm['codigo_maquina_virtual']}'>" .
                    "<img src='{$this->view->baseUrl()}/images/virtual-machine-icon.png'/></a>",
                    "<h4>{$vmCloudSummary['displayname']}</h4><strong>Hardware</strong><p>CPU: {$vmCloudSummary['cpunumber']} de {$vmCloudSummary['cpuspeed']} MHz</p>" .
                    "<p>Memoria: {$vmCloudSummary['memory']} MB</p><strong>Red - {$vmCloudSummary['networkname']}</strong><p>IP: {$vmCloudSummary['ipaddress']}</p><p>GW: {$vmCloudSummary['gateway']}</p>");
            } else {
                $response[] = array("<div class='col-sm-2 col-md-2'>" .
                    "<img src='/images/vm.jpg' style='width: 72px; height: 72px;'>" .
                    "</div>" .
                    "<div class='col-sm-4 col-md-4'>" .
                    "<span class='{$this->vmstateclass($vmCloudSummary['state'])}'><strong>PENDIENTE DE CREACI&Oacute;N</strong></span><br/>");
            }

            echo Zend_Json_Encoder::encode($response);
        }
    }

    public function mylabsAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $aaData = array();
        $response = array();
        try {
            $lab = new VirtualLabs_Academico_Laboratorio();
            $identity = Zend_auth::getInstance()->getIdentity();

            $laboratorios = $lab->getLabsByUsername($identity['username']);

            foreach ($laboratorios as $vLab) {

                $profesores = $lab->getProfesoresByLab($vLab['codigo_laboratorio']);
                $losProfe = "Profesores<br /><ul class=''>";
                foreach ($profesores as $profe) {
                    $losProfe .= "<li class='text-info'>{$profe['nombre']}</li>";
                }
                $losProfe .= "</ul>";

                //$response[] = array("<a id='{$vLab['codigo_laboratorio']}' href='/academico/laboratorioalumno/lab/codigo_laboratorio/{$vLab['codigo_laboratorio']}'>" .
                //    "<img src='{$this->view->baseUrl()}/images/virtual-machine-icon.png'/></a>",
                //    "<strong>{$vLab['nombre_mostrar']} | {$vLab['nombre_area_academica']}</strong><p>{$vLab['descripcion']}</p>", $losProfe);
                $response[] = array(
                    "<div class='col-sm-2 col-md-2'>" .
                    "<img src='/images/vm.jpg' style='width: 72px; height: 72px;'>" .
                    "</div>" .
                    "<div class='col-sm-6 col-md-6'>" .
                    "Laboratorio: <a id='{$vLab['codigo_laboratorio']}' href='/academico/laboratorioalumno/lab/codigo_laboratorio/{$vLab['codigo_laboratorio']}'>" .
                    "<strong>" . $vLab['nombre_mostrar'] . "</strong></a><br/>" .
                    "<span class='text-info'> (" . $vLab['descripcion'] . ") </span><br/>" .
                    "&Aacute;rea acad&eacute;mica: <span class='text-info'>" . $vLab['nombre_area_academica'] . "</span><br/>" .
                    "</div>" .
                    "<div class='col-sm-4 col-md-4'>" .
                    $losProfe .
                    "</div>"
                );
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
            return;
        }

        $aaData['aaData'] = $response;
        //echo Zend_Json_Encoder::encode($response);
        //$aaData['aaData'] = $response;
        echo Zend_Json_Encoder::encode($aaData);
    }

    public function mylabsbyidAction() {
        $this->_helper->layout->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        $cod_lab = $this->getRequest()->getParam('codigo_laboratorio');
        $response = array();

        try {
            $vm = new VirtualLabs_Academico_Laboratorio();
            $identity = Zend_auth::getInstance()->getIdentity();
            $vms = $vm->getVMyLabUsername($cod_lab, $identity['username']);
            foreach ($vms as $vm) {
                $date = new DateTime($vm['fecha_creacion']);
                $d = $date->format('d/m/Y');
                if ($vm['codigo_vm'] != null) {
                    $vmCloudSummary = $this->getVmData($vm['codigo_vm']);
                    $response[] = array(
                        "<div class='col-sm-2 col-md-2'>" .
                        "<img src='/images/vm.jpg' style='width: 70px; height: 70px;'>" .
                        "</div>" .
                        "<div class='col-sm-4 col-md-4'>" .
                        "<a href='/academico/maquinaalumno/vm/codigo_maquina_virtual/{$vm['codigo_maquina_virtual']}'>" . $vmCloudSummary['displayname'] . "</a><br/>" .
                        "<span>Estado: </span><span class='{$vmCloudSummary['state']}'><strong>{$vmCloudSummary['state']}</strong></span>" .
                        "</div>" .
                        "<div class='col-sm-6 col-md-6'>" .
                        "<span><strong>Fecha de Creacion= </strong></span>" . $d . "<br />" .
                        "<span><strong>CPU= </strong></span>" . $vmCloudSummary['cpunumber'] . " de " . $vmCloudSummary['cpuspeed'] . " MHz. " .
                        "<span><strong>Memoria= </strong></span>" . $vmCloudSummary['memory'] . " MB<br />" .
                        "<span><strong>Sistema Operativo= </strong></span>" . $vmCloudSummary['so'] .
                        "</div>"
                    );
                } else {
                    $response[] = array(
                        "<div class='col-sm-2 col-md-2'>" .
                        "<img src='/images/vm.jpg' style='width: 72px; height: 72px;'>" .
                        "</div>" .
                        "<div class='col-sm-4 col-md-4'>" .
                        "<span><strong>PENDIENTE DE CREACI&Oacute;N</strong></span><br/>"
                    );
                }
            }
        } catch (Exception $exc) {
            echo $exc->getTraceAsString();
            return;
        }
        $aaData['aaData'] = $response;
        echo Zend_Json_Encoder::encode($aaData);
    }

    private function getVmData($vmId) {
        $vmCloud = new VirtualLabs_Rest_VirtualLabs_VirtualMachine();
        try {
            $vm = $vmCloud->listVM($vmId);
            $cloudData = Zend_Json_Decoder::decode($vm);
            //$cloudData = $vm;
            return array('name' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['name'],
                'displayname' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['displayname'],
                'state' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['state'],
                'hostid' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['hostid'],
                'cpuspeed' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpuspeed'],
                'cpunumber' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['cpunumber'],
                'serviceofferingname' => $cloudData['listvirtualmachinesresponse'][0]['virtualmachine']['serviceofferingname'],
                'memory' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['memory'],
                'ipaddress' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['ipaddress'],
                'networkname' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['networkname'],
                'gateway' => $cloudData['listvirtualmachinesresponse']['virtualmachine']['nic'][0]['gateway'],
                'so' => $cloudData['listvirtualmachinesresponse']['virtualmachine'][0]['templatedisplaytext']);
        } catch (Exception $e) {
//            $this->debugLog->err($e->getMessage());
//            $this->debugLog->err($e->getTraceAsString());
        }
    }

}